package com.suray.wcs.res.msgparse;


import com.suray.basic.wcs.utils.Crc16;
import com.suray.wcs.res.msgparse.BitsObj;
import com.suray.wcs.res.msgparse.MsgTransferUtil;

import java.util.Arrays;

/**
 * 接受地图反馈
 *
 * @author Doofy&xuhang
 */
public class ReceiveMsgMapData {
    private int index = 32;
    /**
     * 头帧 2字节
     */
    private final int firstFrame = 0x02fd;
    /**
     * 头长度 2字节
     */
    private final int firstMsgLen = 15;
    /**
     * 设备类型 1字节
     */
    private final int deviceType;
    /**
     * 设备号 1字节
     */
    private final int deviceNo;
    /**
     * 模式 1字节
     */
    private final int mode;
    /**
     * ack/nak 1字节
     */
    private final int ack;

    /**
     *  数据包序号 1字节
     */
    private final int dateNum;
    /**
     * 尾长度 2字节
     */
    private final int endMsgLen = 15;
//		/** 信息校验 2字节 */
//		private final int CRC16;
    /**
     * 尾帧 2字节
     */
    private final int endFrame = 0x03fc;


    /**
     * 校验信息是否正确
     */
    private boolean isRight = false;

    public boolean isRight() {
        return isRight;
    }

    public ReceiveMsgMapData(byte[] bs) {
        // 对接收报文的长度进行校验
        if (null == bs) {
            throw new RuntimeException("接收报文为空");
        }
        if (bs.length < firstMsgLen) {
            throw new RuntimeException("报文长度不合法，当前长度:" + bs.length + ",报文内容" + Arrays.toString(bs));
        }
        this.deviceType = getValue(bs, 8);
        this.deviceNo = getValue(bs, 8);
        this.mode = getValue(bs, 8);
        this.ack = getValue(bs, 8);
        this.dateNum = getValue(bs, 8);
        this.isRight = isCRC16Right(bs, bs.length - 4, getValue(bs, 16));
    }

    private BitsObj getBitsObj(byte[] bs, int size) {
        int value = MsgTransferUtil.getValues(bs, index, size);
        BitsObj bitsObj = new BitsObj(size, value);
        index += size;
        return bitsObj;
    }

    private int getValue(byte[] bs, int size) {
        int value = MsgTransferUtil.getValues(bs, index, size);
        index += size;
        return value;
    }
    private boolean isCRC16Right(byte[] bs, int len, int crc16) {
        return Crc16.CRC_XModem(bs, len) == crc16;
    }

    public int getFirstFrame() {
        return firstFrame;
    }

    public int getFirstMsgLen() {
        return firstMsgLen;
    }

    public int getDeviceType() {
        return deviceType;
    }

    public int getDeviceNo() {
        return deviceNo;
    }

    public int getAck() {
        return ack;
    }

    public int getDateNum() {
        return dateNum;
    }

    public int getEndMsgLen() {
        return endMsgLen;
    }

    public int getEndFrame() {
        return endFrame;
    }

    public int getMode() {
        return mode;
    }


}

